from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from models import User, Contribution
from services import update_contributions, allocate_project_profits
from database import get_db

api_router = APIRouter()

@api_router.get("/users")
def get_users(db: Session = Depends(get_db)):
    users = db.query(User).all()
    return [{"id": u.id, "username": u.username} for u in users]

@api_router.get("/getcontributions/{company_id}/{user_id}")
def update_contribution(user_id: int, company_id: int, db: Session = Depends(get_db)):
    if not db.query(User).filter_by(id=user_id).first():
        raise HTTPException(status_code=404, detail="User not found")
    if not db.query(Contribution).filter_by(user_id=user_id, company_id=company_id).first():
        raise HTTPException(status_code=404, detail="Contribution not found")
    contributions = db.query(Contribution).filter_by(user_id=user_id, company_id=company_id).all()
    return {"contributions": [{"project_id": c.project_id, "value": c.value} for c in contributions]}

@api_router.post("/contributions")
def update_contribution(data: dict, db: Session = Depends(get_db)):
    user_id = data["user_id"]
    company_id = data["company_id"]
    new_value = data["new_value"]
    update_contributions(db, user_id, company_id, new_value)
    return {"message": "Contribution updated successfully"}

@api_router.post("/projects/{project_id}/allocate")
def allocate_project_profits_endpoint(project_id: int, db: Session = Depends(get_db)):
    allocate_project_profits(db, project_id)
    return {"message": "Project profits allocated successfully"}


## only for testing purposes
@api_router.get("/allocate/{project_id}/{project_coins}")
def allocate_project_profits_endpoint(project_id: int, project_coins: int, db: Session = Depends(get_db)):
    return allocate_project_profits(db, project_id, project_coins)